package com.fhz.day008.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.fhz.day008.MainActivity;
import com.fhz.day008.R;

import java.util.Timer;
import java.util.TimerTask;


public class ThreeFragment extends Fragment {

    private TextView time;
    private Button send;

    private int index = 5;
    private Timer timer;
    public Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //收到一个消息以后,才开始倒计时;
            if(msg.what == 110){
                //翻页到第三页的时候,开始
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                time.setText(--index+"秒");
                                if(index <= 0 ){
                                    //跳转了
                                    sendEmptyMessage(120);
                                }
                            }
                        });
                    }
                },0,1000);
            }else if(msg.what == 120){
                //跳转了
                timer.cancel();
                startActivity(new Intent(getActivity(),MainActivity.class));
                getActivity().finish();
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_three, container, false);

        time = (TextView) inflate.findViewById(R.id.time);
        send = (Button) inflate.findViewById(R.id.send);


        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        });

        return inflate;
    }
}